
import React, { useEffect, useState } from 'react'
import ReactDOM from 'react-dom/client'
import Dialog from '@mui/material/Dialog'
import ApiDocForm from '@/components/ApiDocForm'
import Snackbar from '@mui/material/Snackbar'
import Alert from '@mui/material/Alert'

function domExtract (callback:(res:Record<string, any>)=>void) {
  const headerRight = document.querySelector('.wiki-view-mode .header-title')
  if (headerRight) {
    const html = document.querySelector('.wiki-preview-body')?.innerHTML
    const router = html?.replace?.(/<.*?>/g, '')?.match?.(/\S+\/\S+/)?.[0]
    const desc = html
    callback({
      name: headerRight?.innerHTML,
      router: router,
      link: location.href,
      desc: desc,
    })
  }
}

function domInject (callback:()=>void) {
  const timer = setInterval(() => {
    const headerRight = document.querySelector('.header-right')
    if (headerRight) {
      clearInterval(timer)
      const div = document.createElement('div')
      div.id = 'addApidoc'
      div.style.padding = '5px'
      div.style.background = '#22B130'
      div.style.color = '#fff'
      div.style.borderRadius = '5px'
      div.style.cursor = 'pointer'
      div.addEventListener('click', () => {
        callback?.()
      })
      div.innerHTML = '添加到ApiDoc'
      headerRight?.append(div)
    }
  }, 500)
}

function App () {
  const [ params, setParams ] = useState<any>(() => ({}))
  const [ msgVisible, setMsgVisible ] = useState(false)
  useEffect(() => {
    domInject(() => {
      domExtract((res) => {
        console.log('抓取结果', res)
        setParams(res)
      })
      setVisible(true)
    })

    // chrome.runtime.sendMessage({}, function (res) {
    //   console.log('发送信息成功', res)
    // })

    // chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    //   console.log(request, sender)
    //   sendResponse('我收到了你的消息！')
    // })

  }, [])

  const [ visible, setVisible ] = useState(false)
  return <React.Fragment>
    <Dialog onClose={() => setVisible(false)} open={visible}>
      <div style={{ width: 500 }}>
        <ApiDocForm
          name={params.name}
          router={params.router}
          link={params.link}
          desc={params.desc}
          onSuccess={() => {
            setVisible(false)
            setMsgVisible(true)
          }}
        />
      </div>
    </Dialog>
    <Snackbar
      anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      open={msgVisible}
      autoHideDuration={2000}
      onClose={() => setMsgVisible(false)}>
      <Alert severity="success">添加成功</Alert>
    </Snackbar>
  </React.Fragment>
}

const root = ReactDOM.createRoot(document.getElementById('my_chrome_anchor')!)
export default root.render(<App />)
